package org.dwpd.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dwpd.mapper.user.FollowMapper;
import org.dwpd.domain.user.Follow;
import org.dwpd.domain.common.Result;
import org.dwpd.domain.user.UserFans;
import org.dwpd.service.user.IFollowService;
import org.dwpd.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.dwpd.utils.RedisConstants.FANS_KEY;
import static org.dwpd.utils.RedisConstants.FOLLOW_KEY;
@Slf4j
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserServiceImpl userService;

    @Override
    public Result follow(Integer followUserId, boolean isFollow) {
        // 1. 获取当前用户ID
        Integer userId = UserHolder.getUser().getUserId();
        log.info("用户关注操作：userId:{}, followUserId:{}, isFollow:{}", userId, followUserId, isFollow);
        String followMessage = null;
        // 2. 判断是关注还是取关操作
        if (isFollow) {
            // 关注
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(userId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                // 若修改数据库成功，则修改redis，将当前用户的关注信息添加到redis集合中
                stringRedisTemplate.opsForSet().add(FOLLOW_KEY + userId, followUserId.toString());
                // 给关注用户添加粉丝缓存
                stringRedisTemplate.opsForSet().add(FANS_KEY + followUserId, userId.toString());
                followMessage = "关注成功";
            }
        }
        else {
            // 取关
            boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
            if (isSuccess) {
                // 若修改数据库成功，则修改redis，将当前用户的关注信息从redis集合中移除
                stringRedisTemplate.opsForSet().remove(FOLLOW_KEY + userId, followUserId.toString());
                // 给关注用户取消粉丝缓存
                stringRedisTemplate.opsForSet().remove(FANS_KEY + followUserId, userId.toString());
                followMessage = "取关成功";
            }
        }
        return Result.success(followMessage != null ? followMessage : "操作失败");
    }

    @Override
    public Result isFollow(Integer followUserId) {
        // 1. 获取当前用户ID
        Integer userId = UserHolder.getUser().getUserId();
        // 2. 判断数据库中是否存在该关注消息
        Long count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        return Result.success(count > 0);
    }

    @Override
    public Result followCommons(Integer id) {
        // 1. 获取当前用户ID -- 集合1
        Integer userId = UserHolder.getUser().getUserId();
        String k1 = FOLLOW_KEY + userId;
        // 2. 获取指定用户的ID -- 集合2
        String k2 = FOLLOW_KEY + id;
        // 3. 从redis中获取两个集合的交集，得到的结果即为两个用户间的共同关注
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(k1, k2);
        if (intersect == null || intersect.isEmpty()){
            // 没有交集，则返回空集合
            return Result.success(Collections.emptyList());
        }
        // 4. 解析结果，将intersect中的数据转为Long类型
        List<Integer> ids = intersect.stream().map(Integer::valueOf).collect(Collectors.toList());
        // 5. ids为共同关注的用户们的ID，通过这些id来获取对应的用户信息
        List<UserFans> userFans = userService.selectFansByIds(ids);
        // 6. 返回结果
        return Result.success(userFans);
    }

    @Override
    public Result fans(Integer userId) {

        if (userId == null || userId <= 0) {
            // 1. 若为空，则表示获取当前登录用户信息，否则获取指定用户粉丝信息
            userId = UserHolder.getUser().getUserId();
        }

        // 2. 从redis中获取当前用户的粉丝信息
        Set<String> members = stringRedisTemplate.opsForSet().members(FANS_KEY + userId);
        if (members == null || members.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        // 3. 解析结果, 将集合中的数据转为Long类型
        List<Integer> ids = members.stream().map(Integer::valueOf).collect(Collectors.toList());
        // 4. ids为所有粉丝的id，通过这些id来获取对应的用户信息
        List<UserFans> userFans = userService.selectFansByIds(ids);
        // 5. 返回结果
        return Result.success(userFans);
    }

    @Override
    public Result follows(Integer userId) {
        if (userId == null || userId <= 0) {
            // 1. 若为空，则表示获取当前登录用户信息，否则获取指定用户关注信息
            userId = UserHolder.getUser().getUserId();
        }
        // 2. 从redis中获取当前用户的关注信息
        Set<String> members = stringRedisTemplate.opsForSet().members(FOLLOW_KEY + userId);
        if (members == null || members.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        // 3. 解析结果, 将集合中的数据转为Long类型
        List<Integer> ids = members.stream().map(Integer::valueOf).collect(Collectors.toList());
        // 4. ids为所有关注用户的id，通过这些id来获取对应的用户信息
        List<UserFans> userFollows = userService.selectFansByIds(ids);
        // 5. 返回结果
        return Result.success(userFollows);
    }
}
